﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace BackupWebRole.MVCHelpers
{
    public static class MVCExtensions
    {
        public static  string ReplaceQuote(this string text)
        {
            return text.Replace("'", "&#39");
        }
        
         
        public static ActionResult TryCatch<T>(this Func<T> a, Func<T,ActionResult> Normal, ActionResult Error, ModelStateDictionary ModelState)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var obj= a();
                    return Normal(obj);
                }
                else
                {
                    return Error;
                }
            }
            catch (Exception ex)
            {
                if (ModelState != null)
                {
                    ModelState.AddModelError("", ex.Message);
                    if (ex.InnerException != null)
                    {
                        ModelState.AddModelError("", ex.InnerException.Message);
                    }
                }

                return Error;
            }
        }
        public static ActionResult TryCatchJson(this Action a)
        {
            try
            {
                a();
                return new JsonResult() {Data = new {isok = true, message = "ok"}};                            
            }
            catch (Exception ex)
            {
                return new JsonResult() { Data = new  { isok = false, message = ex.Message } };   
            }
        }

        public static ActionResult TryCatch( this Action a, ActionResult Normal, ActionResult Error, ModelStateDictionary ModelState)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    a();
                    return Normal;
                }
                else
                {
                    return Error;
                }
            }
            catch (Exception ex)
            {
                if (ModelState != null)
                {
                    ModelState.AddModelError("", ex.Message);
                    if (ex.InnerException != null)
                    {
                        ModelState.AddModelError("", ex.InnerException.Message);
                    }
                }

                return Error;
            }
        }
    }
}